package ui;

import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;

import core.domain.DataFile;
import core.domain.IOUtil;
import core.domain.Torrent;
import core.domain.messages.AbstractMessage.MessageType;
import core.domain.messages.GetFilesMessage;
import core.domain.messages.GetPeersForTorrentMessage;

public class HeadlessLeecher {

	
	private static Socket myPeer;
	private static int port = 13460;
	public static Socket getSocket(){
		try{
		if(myPeer == null){
			myPeer = new Socket("localhost", port);
			return myPeer;
		}else {
			if(!myPeer.isConnected() || myPeer.isClosed()){
				myPeer = new Socket("localhost", port);
			}
			return myPeer;
		}}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	public static void main(String[] args) throws UnknownHostException, IOException {

		
		//		13467
		GetFilesMessage filesMessage = new GetFilesMessage();

		String filesMessageString = IOUtil.getInstance(GetFilesMessage.class).objectToString(filesMessage);
		System.out.println(filesMessageString);
		IOUtil.writeMessageToSocket(getSocket(), filesMessageString, false);
		String responseWithTorrentList = IOUtil.readMessageFromSocket(getSocket(), true);
		System.out.println(responseWithTorrentList);
		GetFilesMessage responseObject = IOUtil.getInstance(GetFilesMessage.class).stringToObject(responseWithTorrentList);
		if(!responseObject.getTorrentFiles().isEmpty()){
			System.out.println("wasn't empty");
			Torrent torrent = Arrays.asList(responseObject.getTorrentFiles().toArray(new Torrent[0])).get(0);
			System.out.println("about to request torrent: " + torrent);
			GetPeersForTorrentMessage getPeersForTorrentMessageRequestObject = new GetPeersForTorrentMessage(torrent);
			String peersforTorrentRequestString = IOUtil.getInstance(GetPeersForTorrentMessage.class).objectToString(getPeersForTorrentMessageRequestObject);
			IOUtil.writeMessageToSocket(getSocket(), peersforTorrentRequestString, true);
			String datafileReceived = IOUtil.readMessageFromSocket(getSocket(), true);
			DataFile data= IOUtil.getInstance(MessageType.matchType(datafileReceived)).stringToObject(datafileReceived);
			data.writeOut();
		}
		while (true) {
		}
	}
	
	
	
	
}
